package com.hulk.common.util.deprecated;

import static com.google.common.base.Preconditions.checkArgument;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.common.base.Objects;

@Slf4j
public class HttpFixClient {

	/**
	 * HTTP Client Object,used HttpClient Class before(version 3.x),but now the
	 * HttpClient is an interface
	 */

	// private CloseableHttpClient client = new CloseableHttpClient();

	/**
	 * Send a XML-Formed string to HTTP Server by post method
	 * 
	 * @param url
	 *            the request URL string
	 * @param xmlData
	 *            XML-Formed string ,will not check whether this string is
	 *            XML-Formed or not
	 * @return the HTTP response status code ,like 200 represents OK,404 not
	 *         found
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String sendXMLDataByPost(String url, String xmlData) {

		return sendXMLDataByPost(url, xmlData, 60000, 60000);
	};

	public static String sendXMLDataByPost(String url, String xmlData,
			int connTimeout, int reqTimeout) {
		
		Integer statusCode = -1;
		RequestConfig config = RequestConfig.custom()
				.setConnectTimeout(connTimeout).setSocketTimeout(reqTimeout)
				.build();
		CloseableHttpClient client = HttpClients.createDefault();
		
//		client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
//	    client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
//	    client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
//	    client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
		HttpPost post = null;
		CloseableHttpResponse response = null;

		try {
			// Send data by post method in HTTP protocol,use HttpPost instead of
			// PostMethod which was occurred in former version
			post = new HttpPost(url);
			
//		    post.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
//		    post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
//		    post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
//		    post.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
			// Construct a string entity
			StringEntity reqentity = new StringEntity(xmlData, StandardCharsets.UTF_8);
			reqentity.setContentType("text/xml;charset=UTF-8");
			reqentity.setContentEncoding( StandardCharsets.UTF_8.name());
			// Set XML entity
			post.setEntity(reqentity);
			// Set content type of request header
			post.setHeader("Content-Type", "text/xml; charset=UTF-8");
//			post.setHeader("Connection", "close");
//			post.getParams().setBooleanParameter("http.protocol.expect-continue", false);
			
			//post.setHeader("Expect", "100-continue");
			//post.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,Boolean.FALSE);

			// Execute request and get the response
			post.setConfig(config);
			response = client.execute(post);
			HttpEntity resentity = response.getEntity();
			
			statusCode = response.getStatusLine().getStatusCode();
			checkArgument(Objects.equal(statusCode, HttpStatus.SC_OK),"响应码状态不是200");
			// httpPost.clone();
			return EntityUtils.toString(resentity);
		} catch (Exception e) {
			log.error("调用HTTP post 服务异常，{}", e);
			return "";
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
					log.error("",e);
				}
			}
			if (post != null) {
				post.releaseConnection();
			}
			if (client != null) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
					log.error("",e);
				}
			}

		}
	}

	public static String sendJsonDataByPost(String url, String jsonData) {

		return sendJsonDataByPost(url, jsonData, 60000, 60000);
	};

	public static String sendJsonDataByPost(String url, String jsonData,
			int connTimeout, int reqTimeout) {
		Integer statusCode = -1;
		RequestConfig config = RequestConfig.custom()
				.setConnectTimeout(connTimeout).setSocketTimeout(reqTimeout)
				.build();
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = null;
		CloseableHttpResponse response = null;

		try {
			// Send data by post method in HTTP protocol,use HttpPost instead of
			// PostMethod which was occurred in former version
			post = new HttpPost(url);
			// Construct a string entity
			StringEntity reqentity = new StringEntity(jsonData, StandardCharsets.UTF_8);
			reqentity.setContentType("application/json;charset=UTF-8");
			reqentity.setContentEncoding( StandardCharsets.UTF_8.name());
			// Set XML entity
			post.setEntity(reqentity);
		
			// Set content type of request header
			post.setHeader("Content-Type", "application/json; charset=UTF-8");
			
			//post.setHeader("Expect", "100-continue");
			// Execute request and get the response
			post.setConfig(config);
			response = client.execute(post);
			HttpEntity resentity = response.getEntity();
			statusCode = response.getStatusLine().getStatusCode();
			checkArgument(Objects.equal(statusCode, HttpStatus.SC_OK),
					"响应码状态不是200");
			// httpPost.clone();
			return EntityUtils.toString(resentity);
		} catch (Exception e) {
			log.error("调用HTTP post 服务异常，{}", e);
			return "";
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
					log.error("",e);
				}
			}
			if (post != null) {
				post.releaseConnection();
			}
			if (client != null) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
					log.error("",e);
				}
			}

		}
	}

	/**
	 * Main method
	 * 
	 * @param args
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void main(String[] args) throws ClientProtocolException,
			IOException {
		String reqXml = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><user><id>1</id><username>larrypage</username></user>";
		
		String retxml = HttpFixClient.sendXMLDataByPost(
				"http://localhost:8888/services/users/register", reqXml);

		System.out.println("Response Code :" + retxml);

	}
}